/*
 * FlightsUI.java
 *
 * Created on 09/10/2011, 20:09:13
 */
package com.bcc.airlines.ui;

import com.bcc.airlines.patterns.Observador;
import com.bcc.airlines.app.Facade;
import com.bcc.airlines.domain.Aeronave;
import com.bcc.airlines.domain.Aeroporto;
import com.bcc.airlines.domain.Voo;
import com.bcc.airlines.ui.effects.TextFieldEffects;
import com.bcc.airlines.util.Tupla;
import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Serginho
 */
public class FlightsUI extends javax.swing.JPanel implements Observador {

    public FlightsUI(MainUI main) {
        this.main = main;
        initComponents();

        main.getFachada().registerDatabaseObserver(this);
        atualiza();
    }

    @Override
    public void atualiza() {
        populateAirplanesCombobox();
        populateAirportsComboboxes();
        updateTable();
    }

    /**
     * Popula os comboboxer com os nomes das aeronaves
     */
    private void populateAirplanesCombobox() {
        Facade fachada = main.getFachada();
        List<Aeronave> aeronaves = fachada.<Aeronave>list(Aeronave.class);

        if (aeronaves != null && !aeronaves.isEmpty()) {
            airplaneComboBox.removeAllItems();
            for (Aeronave a : aeronaves) {
                airplaneComboBox.addItem(a.getNome());
            }
        }
    }

    /**
     * Popula os comboboxes com os destinos dos aeroportos
     */
    private void populateAirportsComboboxes() {
        Facade fachada = main.getFachada();
        List<Aeroporto> aeroportos = fachada.<Aeroporto>list(Aeroporto.class);

        if (aeroportos != null && !aeroportos.isEmpty()) {
            origemComboBox.removeAllItems();
            destinoComboBox.removeAllItems();
            for (Aeroporto a : aeroportos) {
                origemComboBox.addItem(a.getCidade());
                destinoComboBox.addItem(a.getCidade());
            }
        }
    }

    /**
     * Atualiza a tabela
     */
    private void updateTable() {
        // Pede a fachada uma lista de voos cadastrados no sistema
        Facade fachada = main.getFachada();
        List<Voo> voos = fachada.<Voo>list(Voo.class);

        // Pega o modelo da tabela que atualiza os dados
        DefaultTableModel model = (DefaultTableModel) flightsTable.getModel();

        // utilidade para datas
        DateFormat fmt = DateFormat.getDateInstance(DateFormat.MEDIUM);

        // Se a lista de voos nao estiver vazia
        if (voos != null && !voos.isEmpty()) {

            // Apaga tudinho
            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                model.removeRow(i);
            }

            for (Voo v : voos) {
                Object row[] = new Object[6];
                row[0] = v.getIdVoo();
                row[1] = v.getAeronave().getNome();
                row[2] = fmt.format(v.getSaida());
                row[3] = v.getAeroportoByOrigem().getNome();
                row[4] = v.getAeroportoByDestino().getNome();
                model.addRow(row);
            }
        }

        clearFields();
    }

    /**
     * Submete um novo voo
     */
    private void submitFlight() {
        try {
            Facade fachada = main.getFachada();

            String sa = saidaTextField.getText().trim();
            Date saida = DateFormat.getDateInstance().parse(sa);

            String id = (String) airplaneComboBox.getSelectedItem();
            Aeronave a = fachada.<Aeronave>get(Aeronave.class, id);

            String or = (String) origemComboBox.getSelectedItem();
            Aeroporto origem = fachada.<Aeroporto>get(Aeroporto.class, or);

            String des = (String) destinoComboBox.getSelectedItem();
            Aeroporto destino = fachada.<Aeroporto>get(Aeroporto.class, des);

            Voo v = new Voo(0, a, null, origem, destino, 0, saida, saida, null);

            fachada.<Voo>add(Voo.class, v);

            updateTable();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, "Data incorreta");
        }
    }

    /**
     * Remove um voo
     */
    private void removeFlight() {
        Facade fachada = main.getFachada();

        int linha = flightsTable.getSelectedRow();
        String id = (String) flightsTable.getModel().getValueAt(linha, 0);

        Voo v = fachada.<Voo>get(Voo.class, id);
        fachada.<Voo>remove(Voo.class, v);

        updateTable();
    }

    /**
     * O nome ja diz
     */
    private void clearFields() {
        List<Tupla<JTextField, String>> campos = new ArrayList<>();
        campos.add(new Tupla<>(saidaTextField, saidaFieldText));

        TextFieldEffects.clearFields(campos);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        titleLabel = new javax.swing.JLabel();
        quitLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        saidaTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        flightsTable = new javax.swing.JTable();
        removeLabel = new javax.swing.JLabel();
        saveLabel = new javax.swing.JLabel();
        airplaneComboBox = new javax.swing.JComboBox();
        origemComboBox = new javax.swing.JComboBox();
        destinoComboBox = new javax.swing.JComboBox();
        updateLabel = new javax.swing.JLabel();

        setBackground(new java.awt.Color(58, 58, 58));

        jPanel1.setBackground(new java.awt.Color(160, 160, 160));

        titleLabel.setFont(new java.awt.Font("Lucida Sans", 0, 16));
        titleLabel.setForeground(new java.awt.Color(255, 255, 255));
        titleLabel.setText("V�os");

        quitLabel.setFont(new java.awt.Font("Lucida Sans", 1, 16));
        quitLabel.setForeground(new java.awt.Color(255, 255, 255));
        quitLabel.setText("X");
        quitLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                quitLabelMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(titleLabel)
                .add(57, 57, 57)
                .add(quitLabel)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(quitLabel)
                .add(titleLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        jPanel2.setOpaque(false);

        saidaTextField.setForeground(new java.awt.Color(119, 167, 243));
        saidaTextField.setText("Sa�da");
        saidaTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                saidaTextFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                saidaTextFieldFocusLost(evt);
            }
        });

        flightsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "N�mero", "Aeronave", "Sa�da", "Origem", "Destino", "Vagas"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(flightsTable);

        removeLabel.setForeground(new java.awt.Color(255, 255, 255));
        removeLabel.setText("Remover");
        removeLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                removeLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                removeLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                removeLabelMouseExited(evt);
            }
        });

        saveLabel.setForeground(new java.awt.Color(255, 255, 255));
        saveLabel.setText("Salvar");
        saveLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                saveLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                saveLabelMouseExited(evt);
            }
        });

        airplaneComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Aeronave" }));

        origemComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Origem" }));

        destinoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Destino" }));

        updateLabel.setForeground(new java.awt.Color(255, 255, 255));
        updateLabel.setText("Atualizar");
        updateLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                updateLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                updateLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                updateLabelMouseExited(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(origemComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 107, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(destinoComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 107, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(airplaneComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 107, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(saidaTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 138, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(saveLabel)
                        .add(18, 18, 18)
                        .add(removeLabel)
                        .add(18, 18, 18)
                        .add(updateLabel))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 739, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2Layout.linkSize(new java.awt.Component[] {airplaneComboBox, destinoComboBox, origemComboBox, saidaTextField}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 138, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(saveLabel)
                    .add(removeLabel)
                    .add(updateLabel))
                .add(18, 18, 18)
                .add(saidaTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(airplaneComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(origemComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(destinoComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap(808, Short.MAX_VALUE)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(175, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(157, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void quitLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_quitLabelMouseClicked
    main.Return();
}//GEN-LAST:event_quitLabelMouseClicked

private void saveLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveLabelMouseClicked
    submitFlight();
}//GEN-LAST:event_saveLabelMouseClicked

private void removeLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseClicked
    removeFlight();
}//GEN-LAST:event_removeLabelMouseClicked

private void updateLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateLabelMouseClicked
    updateTable();
}//GEN-LAST:event_updateLabelMouseClicked

private void saveLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveLabelMouseEntered
    ((JLabel) evt.getSource()).setForeground(new Color(132, 180, 254));
}//GEN-LAST:event_saveLabelMouseEntered

private void removeLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseEntered
    ((JLabel) evt.getSource()).setForeground(new Color(132, 180, 254));
}//GEN-LAST:event_removeLabelMouseEntered

private void updateLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateLabelMouseEntered
    ((JLabel) evt.getSource()).setForeground(new Color(132, 180, 254));
}//GEN-LAST:event_updateLabelMouseEntered

private void saveLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveLabelMouseExited
    ((JLabel) evt.getSource()).setForeground(Color.white);
}//GEN-LAST:event_saveLabelMouseExited

private void removeLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseExited
    ((JLabel) evt.getSource()).setForeground(Color.white);
}//GEN-LAST:event_removeLabelMouseExited

private void updateLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateLabelMouseExited
    ((JLabel) evt.getSource()).setForeground(Color.white);
}//GEN-LAST:event_updateLabelMouseExited

    private void saidaTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_saidaTextFieldFocusGained
        if (saidaTextField.getText().equals(saidaFieldText)) {
            TextFieldEffects.activeTextField(saidaTextField);
        }
    }//GEN-LAST:event_saidaTextFieldFocusGained

    private void saidaTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_saidaTextFieldFocusLost
        if (saidaTextField.getText().equals("")) {
            TextFieldEffects.ociousTextField(saidaTextField, saidaFieldText);
        }
    }//GEN-LAST:event_saidaTextFieldFocusLost
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox airplaneComboBox;
    private javax.swing.JComboBox destinoComboBox;
    private javax.swing.JTable flightsTable;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox origemComboBox;
    private javax.swing.JLabel quitLabel;
    private javax.swing.JLabel removeLabel;
    private javax.swing.JTextField saidaTextField;
    private javax.swing.JLabel saveLabel;
    private javax.swing.JLabel titleLabel;
    private javax.swing.JLabel updateLabel;
    // End of variables declaration//GEN-END:variables
    private MainUI main;
    private String saidaFieldText = "Saida";
}
